package frame.Customer;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.CustomerMapper;
import org.example.pojo.Customer;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class customerupdate extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private SqlSession sqlSession;
    private CustomerMapper customerMapper;

    public customerupdate() {
        sqlSession = MyBatislianjian.getSqlSession();
        customerMapper = sqlSession.getMapper(CustomerMapper.class);

        setTitle("修改客户信息");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
        table = new JTable() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return true; // 设置单元格可编辑
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // 设置多选模式

        // 初始化表格数据
        initializeTableData();

        // 将表格及其滚动面板添加到中心区域
        JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板并添加到 SOUTH 区域
        JPanel buttonPanel = new JPanel();
        JButton updateButton = new JButton("确定修改");
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateCustomers(); // 点击确定修改按钮时执行更新操作
            }
        });
        JButton addButton1 = new JButton("返回");
        addButton1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new CustomerPanel());
            }
        });
        buttonPanel.add(updateButton);
        buttonPanel.add(addButton1);
        this.add(buttonPanel, BorderLayout.SOUTH);
    }

    // 初始化表格数据
    private void initializeTableData() {
        Object[] columnNames = {"客户编号", "公司名称", "公司简称", "公司地址", "公司电话", "公司邮件", "联系人姓名", "联系人电话", "备注"};
        List<Customer> customers = customerMapper.selectAll();

        // 动态生成数据数组
        Object[][] data = new Object[customers.size()][columnNames.length];
        for (int i = 0; i < customers.size(); i++) {
            Customer customer = customers.get(i);
            data[i][0] = customer.getCid();
            data[i][1] = customer.getCcompanyName();
            data[i][2] = customer.getCcompanySName();
            data[i][3] = customer.getCcompanyAddress();
            data[i][4] = customer.getCcompanyPhone();
            data[i][5] = customer.getCemail();
            data[i][6] = customer.getCName();
            data[i][7] = customer.getCtelPhone();
            data[i][8] = customer.getOther();
        }

        tableModel = new DefaultTableModel(data, columnNames);
        table.setModel(tableModel);
    }

    // 更新客户信息到数据库
    private void updateCustomers() {
        int rowCount = table.getRowCount();
        boolean hasChanges = false; // 检查是否有任何数据变化

        for (int row = 0; row < rowCount; row++) {
            String cid = ((String) table.getValueAt(row, 0)).trim();
            String companyName = ((String) table.getValueAt(row, 1)).trim();
            String companySName = ((String) table.getValueAt(row, 2)).trim();
            String companyAddress = ((String) table.getValueAt(row, 3)).trim();
            String companyPhone = ((String) table.getValueAt(row, 4)).trim();
            String companyEmail = ((String) table.getValueAt(row, 5)).trim();
            String contactName = ((String) table.getValueAt(row, 6)).trim();
            String contactPhone = ((String) table.getValueAt(row, 7)).trim();
            String other = ((String) table.getValueAt(row, 8)).trim();

            // 检查关键字段不能为空字符
            if (cid.isEmpty() || companyName.isEmpty() || companySName.isEmpty()
                    || companyAddress.isEmpty() || contactName.isEmpty() || contactPhone.isEmpty()) {
                JOptionPane.showMessageDialog(this, "每一行的客户编号、公司名称、公司简称、公司地址、联系人姓名、联系人电话都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 获取原始数据
            Customer originalCustomer = customerMapper.selectByCid(cid);
            if (originalCustomer != null) {
                // 检查数据是否有变化
                if (!originalCustomer.getCcompanyName().equals(companyName)
                        || !originalCustomer.getCcompanySName().equals(companySName)
                        || !originalCustomer.getCid().equals(cid)
                        || !originalCustomer.getCcompanyAddress().equals(companyAddress)
                        || !originalCustomer.getCcompanyPhone().equals(companyPhone)
                        || !originalCustomer.getCemail().equals(companyEmail)
                        || !originalCustomer.getCName().equals(contactName)
                        || !originalCustomer.getCtelPhone().equals(contactPhone)
                        || !originalCustomer.getOther().equals(other)) {
                    // 更新数据库中的客户信息
                    Customer updatedCustomer = new Customer(cid, companyName, companySName, companyAddress, companyPhone, companyEmail, contactName, contactPhone, other);
                    customerMapper.update(updatedCustomer);
                    hasChanges = true; // 标记有变化
                }
            }
        }

        if (hasChanges) {
            JOptionPane.showMessageDialog(this, "客户信息已更新！", "提示", JOptionPane.INFORMATION_MESSAGE);
            // 刷新表格数据
            refreshTableData();
        } else {
            JOptionPane.showMessageDialog(this, "没有检测到任何更改。", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // 刷新表格数据的方法
    private void refreshTableData() {
        List<Customer> customers = customerMapper.selectAll();

        // 清除现有数据
        tableModel.setRowCount(0);

        // 添加新的数据
        for (Customer customer : customers) {
            tableModel.addRow(new Object[]{
                    customer.getCid(),
                    customer.getCcompanyName(),
                    customer.getCcompanySName(),
                    customer.getCcompanyAddress(),
                    customer.getCcompanyPhone(),
                    customer.getCemail(),
                    customer.getCName(),
                    customer.getCtelPhone(),
                    customer.getOther()
            });
        }
    }
}
